package cn.cqnu.controller.front;

import cn.cqnu.domin.entity.Student;
import cn.cqnu.domin.vo.ResponseResult;
import cn.cqnu.domin.vo.StudentInfoVo;
import cn.cqnu.global.SystemConstant;
import cn.cqnu.global.SystemReturnEnum;
import cn.cqnu.service.StudentService;
import cn.cqnu.utils.JWTUtils;
import cn.cqnu.utils.OSSUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Map;

@RestController
@RequestMapping("/front/stu")
public class StudentController {

    @Autowired
    StudentService studentService;
    @PostMapping("/uploadAvatar")
    public ResponseResult uploadAvatar(MultipartFile file, HttpServletRequest request) {
        if (file == null) {
            return ResponseResult.error(SystemReturnEnum.FILE_TYPE_ERR);
        } else {
            String originalFilename = file.getOriginalFilename();
            Path path = Paths.get(originalFilename);
            if (Files.isDirectory(path)) {
                return ResponseResult.error(SystemReturnEnum.FILE_TYPE_ERR);
            }
        }

        //获取文件的扩展名
        String temp = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".")).toLowerCase();

        //校验文件类型是否为图片
        if (!temp.equals(".jpg") && !temp.equals(".jpeg") && !temp.equals(".png")) {
            return ResponseResult.error(SystemReturnEnum.FILE_TYPE_ERR);
        }

        //设置背景图片文件名为时间戳
        // TODO 修改为学生学号
        Map<String, Object> payload = JWTUtils.getPayload(request.getHeader("token"));
        String studentId = String.valueOf(payload.get("id"));
        String fileName = studentId + temp;

        try {
            String backImgUrl = OSSUtil.uploadFile(file.getInputStream(), SystemConstant.OSS_AVATAR_PATH, fileName);
            System.out.println(backImgUrl);
            //TODO 保存到数据库中
            return ResponseResult.ok();
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseResult.error(SystemReturnEnum.FILE_TYPE_ERR);
        }
    }
    @GetMapping("/getStuById/{id}")
    public ResponseResult getStuById(@PathVariable String stuId){
        StudentInfoVo result = studentService.getStuById(stuId);
        return ResponseResult.ok(result);
    }
    @PostMapping("/updateStu")
    public ResponseResult updateStu(@RequestBody Student studentInfo){
        studentService.updateStuInfo(studentInfo);
        return ResponseResult.ok();
    }

    @GetMapping("/signOff/{id}")
    public ResponseResult signOffById(@PathVariable String id){
        studentService.signOffById(id);
        return ResponseResult.ok();
    }

}
